//
//  MeSetUsetImgVC.m
//  ZITHER
//
//  Created by weixin on 2018/11/23.
//  Copyright © 2018 weixn. All rights reserved.
//

#import "MeSetUsetImgVC.h"
#import "MeSetUsetImg.h"
// 引入以下2个类
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

@interface MeSetUsetImgVC ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate,QMUIImagePreviewViewDelegate>
@property(nonatomic, strong) QMUIImagePreviewViewController *imagePreviewViewController;

@property (nonatomic,strong)BaseImageV * userPic;
@end

@implementation MeSetUsetImgVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getNav];
    [self setUI];

    [RACObserve(kUSER_INFO_MANAGER, avatar)subscribeNext:^(id  _Nullable x) {
        [self userPic];
    }];
}

-(void)setUI{
    [self.view addSubview:self.userPic];
    [self.userPic mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view).offset(0);
        make.height.width.mas_equalTo(kScreenW);
    }];
}

-(void)getNav{
    
    [self.baseNavigationView NavigationBarStyle:1];
    self.baseNavigationView.leftButton1.hidden = YES;
    self.baseNavigationView.isShowShadow = YES;
    self.baseNavigationView.navViewStyle.title.text = @"我的头像";

    /* TODO: ================= 导航栏箭头颜色 =================*/
        QMUIButton *btnTrash = [[QMUIButton alloc]initWithFrame:CGRectMake(kScreenW-60,kStatusBarHeight+5,40,40)];
        [btnTrash setImage:[UIImage imageNamed:@"nav_btn_more"] forState:UIControlStateNormal];
        [self.baseNavigationView.navViewStyle addSubview:btnTrash];
    
        btnTrash.centerY = self.baseNavigationView.navViewStyle.title.centerY;
        @weakify(self);
        [[btnTrash rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            /* MARK: ================= 弹出头像弹窗 =================*/
            
            QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
                
            }];
            
            
            QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"从手机相册选择" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
                [self presentImagePicker];
            }];
            
            QMUIAlertAction *action4 = [QMUIAlertAction actionWithTitle:@"使用系统头像" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
                
                MeSetUsetImg *vc = [[MeSetUsetImg alloc]init];
                [vc setBlock:^{
                    [self upPic];
                }];
                [self.navigationController pushViewController:vc animated:YES];
            }];
            
            QMUIAlertAction *action5 = [QMUIAlertAction actionWithTitle:@"拍照" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
                UIImagePickerController *pickerCon = [[UIImagePickerController alloc]init];
                pickerCon.sourceType = UIImagePickerControllerSourceTypeCamera;
                pickerCon.allowsEditing = NO;//是否可编辑
                pickerCon.delegate = self;
                [self presentViewController:pickerCon animated:YES completion:nil];
            }];
            
            
            
            QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
            
            [alertController addAction:action1];
            [alertController addAction:action5];
            [alertController addAction:action2];
            [alertController addAction:action4];
            
            [alertController showWithAnimated:YES];
        }];
    
}


/* MARK: ================= 上传用户头像图片 =================*/
#pragma mark - 打开图片浏览器
-(void)presentImagePicker{
    TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    picker.allowPickingVideo = NO;
    picker.allowTakeVideo = NO;
    
    [picker setDidFinishPickingPhotosWithInfosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
        
        if (photos.count > 0) {
            
            // 添加了图片 先上传到服务器
            UIImage *image = photos.firstObject;
            //上传腾讯云服务器上
            [kNetworkShared getImageURLWithImage:image completion:^(COSObjectUploadTaskRsp *uploadTaskRsp, NSString *filePath, NSString *fileName, BOOL isSuccess, NSError *error) {
                
                if (isSuccess) {
                    
                    NSString * avatar = kSTRING_FORMAT(@"%@/%@",filePath,fileName);
                    //                NSDictionary *dic = @{@"token":kUSER_INFO_MANAGER.token,@"avatar":avatar,@"id":kUSER_INFO_MANAGER.userId};
                    NSLog(@"");
                    @weakify(self);
                    [[AccountService loadsaveUserAvatar:avatar]subscribeNext:^(ResponseData *x) {
                        @strongify(self);
                        if (x.success) {
                            [Tools showTips:@"修改成功"];
                            
                            kUSER_INFO_MANAGER.avatar = avatar;
                            [kUSER_INFO_MANAGER MyList];
                            [self upPic];
//                            [self.navigationController popViewControllerAnimated:YES];
                            
                            //                            [[AccountService loadLogin:str phoneCode:@"8888" reponseObjctClass:[UserInfoManager class]]subscribeNext:^(ResponseData * x) {
                            //                                if (x.success) {
                            //                                    [kUSER_INFO_MANAGER MyList];
                            //                                    ResponseData *data = x;
                            //                                    UserInfoManager *model = data.responseData;
                            //                                    [kUSER_INFO_MANAGER setUserInfoWithModel:model];
                            //                                }else{
                            //                                    [QMUITips showError:x.errorInfo];
                            //                                }
                            ////                                [self.navigationController popViewControllerAnimated:YES];
                            //                            }];
                            
                        }else{
                            [QMUITips showError:x.errorInfo];
                        }
                    }];
                }else{
                    [QMUITips showError:@"上传失败"];
                }
            }];
            
        }
        
    }];
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

/** 修改图片以后 */
-(void)upPic{
    [self.userPic sd_setImage:kUSER_INFO_MANAGER.avatar];
}

-(BaseImageV *)userPic{
    if (!_userPic) {
        _userPic = [[BaseImageV alloc]initializeFrame:CGRectMake(0, 0, 0, 0) contentMode:2];
        [_userPic sd_setImage:kUSER_INFO_MANAGER.avatar];
        [[_userPic addTag]subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            NSLog(@"123");
            [self showBigImage:100];
        }];
    }
    return _userPic;
}



-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {//如果是拍照
        UIImage *image;
        //如果允许编辑则获得编辑后的照片，否则获取原始照片
        if (picker.allowsEditing) {
            image=[info objectForKey:UIImagePickerControllerEditedImage];//获取编辑后的照片
        }else{
            image=[info objectForKey:UIImagePickerControllerOriginalImage];//获取原始照片
        }
        self.userPic.image = image;
        [self upUserPic];
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);//保存到相簿
    }
//    else if([mediaType isEqualToString:(NSString *)kUTTypeMovie]){//如果是录制视频
//        NSLog(@"video...");
//        NSURL *url=[info objectForKey:UIImagePickerControllerMediaURL];//视频路径
//        NSString *urlStr=[url path];
//        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
            //保存视频到相簿，注意也可以使用ALAssetsLibrary来保存
//            UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);//保存视频到相簿
//        }
//    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];

}


-(void)upUserPic{
    //上传腾讯云服务器上
        [kNetworkShared getImageURLWithImage:self.userPic.image completion:^(COSObjectUploadTaskRsp *uploadTaskRsp, NSString *filePath, NSString *fileName, BOOL isSuccess, NSError *error) {
            
            if (isSuccess) {
                
                NSString * avatar = kSTRING_FORMAT(@"%@/%@",filePath,fileName);
                NSLog(@"");
                @weakify(self);
                [[AccountService loadsaveUserAvatar:avatar]subscribeNext:^(ResponseData *x) {
                    @strongify(self);
                    if (x.success) {
                        //更新用户数据
                        kUSER_INFO_MANAGER.avatar = avatar;
                        [kUSER_INFO_MANAGER MyList];
                        
//                        [self.navigationController popViewControllerAnimated:YES];
                        [QMUITips  showSucceed:@"修改成功"];
                        [self upPic];
                    }else{
                         [Tools showTips:x.errorInfo];
                    }
                    
                }];
            }else{
                [Tools showTips:@"上传失败"];
            }
            
        }];
}




-(void)showBigImage:(NSInteger)selectIndex{
    UIImageView *imageV = self.userPic;
    // self.model.fileList[selectIndex-100];
    
    if (!self.imagePreviewViewController) {
        self.imagePreviewViewController = [[QMUIImagePreviewViewController alloc] init];
        self.imagePreviewViewController.imagePreviewView.delegate = self;
        
        // QMUIImagePreviewViewController 对于以 window 的方式展示的情况，默认会开启手势拖拽退出预览功能。
        // 如果使用了手势拖拽，并且退出预览时需要飞到某个 rect，则需要实现这个 block，在里面自己去 exit，如果不实现这个 block，退出动画会使用 fadeOut 那种
        
    }
    @weakify(self);
    self.imagePreviewViewController.customGestureExitBlock = ^(QMUIImagePreviewViewController *aImagePreviewViewController, QMUIZoomImageView *currentZoomImageView) {
        @strongify(self);
        UIImageView *imageV1 = self.userPic;
        
        [aImagePreviewViewController exitPreviewToRectInScreenCoordinate:[self.userPic convertRect:self.userPic.frame toView:nil]];
        
    };
    self.imagePreviewViewController.imagePreviewView.currentImageIndex =  selectIndex-100;// 默认查看的图片的 index
    
    [self.imagePreviewViewController startPreviewFromRectInScreenCoordinate:[self.userPic convertRect:self.userPic.frame toView:nil] cornerRadius:self.userPic.layer.cornerRadius];
}


#pragma mark - <QMUIImagePreviewViewDelegate>

- (NSUInteger)numberOfImagesInImagePreviewView:(QMUIImagePreviewView *)imagePreviewView {
    return 1;
}

- (void)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView renderZoomImageView:(QMUIZoomImageView *)zoomImageView atIndex:(NSUInteger)index {
    // 模拟异步加载的情况
    zoomImageView.reusedIdentifier = @(index);
    [zoomImageView showLoading];
    
    UIImageView *imageV = self.userPic;
    [zoomImageView hideEmptyView];
    zoomImageView.image = imageV.image;
    
}

- (QMUIImagePreviewMediaType)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView assetTypeAtIndex:(NSUInteger)index {
    return QMUIImagePreviewMediaTypeImage;
}

#pragma mark - <QMUIZoomImageViewDelegate>

- (void)singleTouchInZoomingImageView:(QMUIZoomImageView *)zoomImageView location:(CGPoint)location {
    //点击缩回
    self.imagePreviewViewController.customGestureExitBlock(self.imagePreviewViewController, zoomImageView);
}
@end
